#include <stdio.h>
#include <string.h>
#include "message.h"
#include "sir.h"
#include <time.h>

char pluginName[255] = "toFile";
char subject[255]    = "";
FILE * fp = NULL;
char fileName[255];
char timestamp[255];

int init( char * _subject, sirElement * config )
{
	int cr = 1;

	if ( _subject != NULL )
	{
		strcpy ( subject, _subject );
	}	
	printf("Init plugin %s listenning %s \n", pluginName, subject);

	char nomSection[ STRING_SIZE ];
	sprintf(nomSection, "%s:%s", pluginName, subject );
	if ( ! isSectionExists( config, nomSection ) )
	{
		strcpy(nomSection, pluginName );
	}

	
	if ( config != NULL )
	{
		sirElement * search = getElement( config, nomSection, "fileOut" );
		strcpy( fileName, getElementValue( search, "") );

		search = getElement( config, nomSection, "timestamp" );
		if (search != NULL )
		{
			strcpy( timestamp, getElementValue( search, "") );
		}
		
	}
	if ( strcmp( "", fileName ) == 0 )
	{
		if ( strcmp( subject, "" ) != 0 )
		{
			sprintf(fileName, "%s.csv", subject);
		}
		else
		{
			sprintf(fileName, "%s.csv", pluginName);
		}
	}
	printf("Openning file %s \n", fileName);
	fp = fopen(fileName, "a");
	if ( fp == NULL )
	{
		return 0;
	}
	return cr;
}

char * parse ( Message * message )
{

	if ( fp != NULL )
	{
//		printf("Ecriture dans le fichier %s\n", fileName );
		if ( strcasecmp( timestamp, "TRUE" ) == 0)
		{
			time_t rawtime;
			struct tm * timeinfo;

			time ( &rawtime );
			timeinfo = localtime ( &rawtime );			
			fprintf(fp, "%04d%02d%02d.%02d%02d%02d;" 
			        ,timeinfo->tm_year + 1900
					,timeinfo->tm_mon + 1
			        ,timeinfo->tm_mday
			        ,timeinfo->tm_hour
			        ,timeinfo->tm_min
			        ,timeinfo->tm_sec
			        );
		}
		fprintf(fp, "%s\n", message->message);
		fflush( fp);
	}

	return message->message;
}

